package qc.module.platform.mapper;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
import qc.common.core.enums.RequestMethodEnum;
import qc.module.platform.dto.api.APIDto;
import qc.module.platform.entity.QcApis;

import java.util.ArrayList;
import java.util.List;

/**
 * ApiMapper
 *
 * @author QuCheng Tech
 * @create 2024/5/6
 */
@Mapper
public interface ApiMapper {
    ApiMapper MAPPER = Mappers.getMapper(ApiMapper.class);

    @Mapping(target = "method", ignore = true)
    QcApis toEntity(APIDto dto);

    @Mapping(target = "method", source = "method.index")
    APIDto toDto(QcApis en);
    
    List<APIDto> toDtoList(List<QcApis> enList);


    /**
     * dtoList转换为entityList
     * 
     * @param dtoList
     * @return List<QcApis>
     * @author QuCheng Tech
     * @since 2024/5/7
     */
    default List<QcApis> toEntityList(List<APIDto> dtoList){
        List<QcApis> ens = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(dtoList)){
            for (APIDto dto : dtoList){
                QcApis en = dtoToEntity(dto);
                ens.add(en);
            }
        }
        return ens;
    }

    /**
     * DTO转换为Entity
     *
     * @param dto 新增DTO
     * @return Entity
     * @author QuCheng Tech
     * @since 2024/5/6
     */
    default QcApis dtoToEntity(APIDto dto) {
        //DTO转换为Entity
        QcApis en = ApiMapper.MAPPER.toEntity(dto);
        //处理数据类型，非空时进行转换，空值时使用默认
        Integer method = dto.getMethod();
        en.setMethod(getRequestMethodEnum(method));
        return en;
    }

    static RequestMethodEnum getRequestMethodEnum(Integer index) {
        if (index != null && index > 0x0) {
            for (RequestMethodEnum item : RequestMethodEnum.values()) {
                if (item.getIndex() == index) {//判断序号使用getIndex，判断内容使用getName
                    return item;
                }
            }
        }
        return RequestMethodEnum.GET;
    }
}
